package com.csqiusheng.zyydt.model

import androidx.lifecycle.viewModelScope
import com.csqiusheng.base.bean.ResultBean
import com.csqiusheng.base.bean.ResultException
import com.csqiusheng.base.utils.LogUtil
import com.csqiusheng.base.utils.showToast
import com.csqiusheng.zyydt.ui.activity.LoginActivity
import com.csqiusheng.zyydt.ui.activity.UserPerfectVolunteerActivity
import com.csqiusheng.zyydt.utils.Navigation
import com.csqiusheng.zyydt.utils.UserSp
import kotlinx.coroutines.*

open class BaseViewModel : com.csqiusheng.base.mvvm.BaseViewModel() {

    fun <T> http(
        api: suspend CoroutineScope.() -> ResultBean<T>,
        complete: () -> Unit = {},
        success: (T?) -> Unit = {},
        error: (Exception) -> Unit = {},
    ) {
        viewModelScope.launch {
            try {
                val bean = withContext(Dispatchers.IO) {
                    api()
                }
                if (bean.code == "0000") {
                    success(bean.result)
                    successHttp.value=bean.message
                } else {
                    if(bean.code=="1001" || bean.code=="1002" ||bean.code=="1006"|| bean.code=="1009"|| bean.code=="1003"){//登录失效等
                        UserSp.setToken(null)
                        UserSp.setUser(userInfo = null)
                        bean.message?.showToast()
                        Navigation.startActivityTop(LoginActivity::class.java)
                    }else if(bean.code=="2018"){//未完成信息
                        Navigation.startActivity(UserPerfectVolunteerActivity::class.java)
                    }
                    val e = ResultException(bean.code, bean.message)
                    error(e)
                    errorHttp.value=bean.message
                }
            } catch (exception: Exception) {
                LogUtil.i("http",exception.toString())
                val e = ResultException("-1", "网络数据错误")
                error(e)
                errorHttp.value=e.message
            } finally {
                complete()
                completeHttp.call()
                topProgressDialog.call()
                centerProgressDialog.call()
            }

        }
    }


}